package com.xydtech.common.config.activemq;

import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.unipush.domain.UniPushMessageContent;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.annotation.JmsListenerConfigurer;
import org.springframework.jms.config.JmsListenerEndpointRegistrar;
import org.springframework.jms.config.SimpleJmsListenerEndpoint;

import javax.jms.Destination;
import javax.jms.JMSException;

/**
 * activemq配置
 * @author Daniel
 * @date 2022-3-15
 */
@Configuration
@EnableJms
public class ActiveMqConfig implements JmsListenerConfigurer {


    /**
     * 发布/订阅模式队列名称
     */
    public static final String TOPIC_NAME = "activemq.topic";
    /**
     * 点对点模式队列名称
     */
    public static final String APP_MESSAGE_QUEUE_NAME = "activemq.app.message.queue";
    @Value("${busiplat.MQEnabled}")
    private Boolean mqEnabled;

    /**
     * 订阅/发布模式（暂时还没用这个）
     * @param
     * @return javax.jms.Destination
     * @exception
     * @author Daniel
     * @date 2022/3/16 13:40
     */
    @Bean
    public Destination topic() {
        return new ActiveMQTopic(TOPIC_NAME);
    }

    /**
     * 注入app消息通知队列
     * @param
     * @return javax.jms.Destination
     * @exception
     * @author Daniel
     * @date 2022/3/16 8:36
     */
    @Bean
    public Destination appMessageQueue() {
        return new ActiveMQQueue(APP_MESSAGE_QUEUE_NAME);
    }

    /**
     * 添加ActiveMQ监听处理消息队列内容
     *
     * @param registrar
     * @return void
     * @exception
     * @author Daniel
     * @date 2022/3/23 10:06
     */
    @Override
    public void configureJmsListeners(JmsListenerEndpointRegistrar registrar) {

        //APP端消息推送监听及消费处理代码
        if (mqEnabled) {
            SimpleJmsListenerEndpoint endpoint = new SimpleJmsListenerEndpoint();
            endpoint.setId(ActiveMqConfig.APP_MESSAGE_QUEUE_NAME);
            endpoint.setDestination(ActiveMqConfig.APP_MESSAGE_QUEUE_NAME);
            endpoint.setConcurrency("10-1000");
            endpoint.setMessageListener(message -> {
                try {
                    UniPushMessageContent uniPushMessageContent = JSONObject.parseObject(((ActiveMQTextMessage) message).getText(), UniPushMessageContent.class);
                    //TODO 推送注释
                    //uniPushService.sendAppMessageToSignle(uniPushMessageContent);
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            });
            registrar.registerEndpoint(endpoint);
        }
    }
}
